<template>
	<view v-if="refreshed">
        <image class="viewImage" :src="urlto" v-if="isImage" mode="widthFix"></image>
		<web-view :webview-styles="webviewStyles" :src="urlto" class="iframepage" @message="onGetMessage" v-else></web-view>
	</view>
</template>

<script>
	import sceneMixins from '@/utils/sceneMixins';
	export default {
		mixins: [sceneMixins],
		data() {
			return {
				urlto:'',
                isImage: true,
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				},
				refreshed: true
			
			}
		},
		onShow: function () {
			if (this.needRefresh) {
				this.refreshed = false;
				setTimeout(() => {
					this.refreshed = true;
				}, 200);
			}
		},
        onShareTimeline(options) {
			var vm = this;
			let routes = getCurrentPages();
			let route = routes[routes.length - 1];
			let curParam = route.options;
			var shareObj = {path: route.route, options: curParam};
            
			return {
				title: ' ',
				path: 'pages/index/index?share=' + encodeURIComponent(JSON.stringify(shareObj)),
				success(res) {
					uni.showToast({
					title: '分享成功'
					})
				},
				fail(res) {
					uni.showToast({
					title: '分享失败',
					icon: 'none'
					})
				}
			}
		},
		onShareAppMessage(options) {
			var vm = this;
			let routes = getCurrentPages();
			let route = routes[routes.length - 1];
			let curParam = route.options;
			var shareObj = {path: route.route, options: curParam};

			console.log('pages/index/index?share=' + encodeURIComponent(JSON.stringify(shareObj)));
			return {
				title: ' ',
				path: 'pages/index/index?share=' + encodeURIComponent(JSON.stringify(shareObj)),
				success(res) {
					uni.showToast({
					title: '分享成功'
					})
				},
				fail(res) {
					uni.showToast({
					title: '分享失败',
					icon: 'none'
					})
				}
			}
		},
		onLoad(options) {
			var vm = this;
			if (options.title) {
				uni.setNavigationBarTitle({
					title: options.title
				});
				vm.title = options.title;
			}
	
            var url = decodeURIComponent(options.url);
			if (url.includes('needRefresh')) {
				this.needRefresh = true;
			}
            this.isImage = url.endsWith('.png');
			this.doWxLogin().then(res => {
				url = url.replace('【openId】', res.openId)
				.replace('【token】', res.token)
				.replace('【timeStamp】', new Date().getTime())
				.replace('【lnglat】', this.$store.state.lnglat);

                var defaultUrlPrefix = vm.API_PREFIX;
				// #ifdef MP-WEIXIN
                if (__wxConfig.envVersion != 'develop') {
                    defaultUrlPrefix = defaultUrlPrefix.replace(/:[1-9]\d*/, '');
                } else {
					if (global.localJSONConfigStarted == 'true') {
						if (url.includes('.html')) {
							defaultUrlPrefix = vm.LocalTestServer;
							url = url.replace(vm.WX_ASSETS, '/wxAssets');
						}
					}
				}
				console.log((url.startsWith('http') ? '' : defaultUrlPrefix) + url);
				this.urlto = (url.startsWith('http') ? '' : defaultUrlPrefix) + url;
				// #endif
				
				// #ifdef H5
				if (location.hostname != 'localhost') {
                    defaultUrlPrefix = defaultUrlPrefix.replace(/:[1-9]\d*/, '');
                }
				console.log(url);
				if (url.includes('needWebview')) {
					this.urlto = url;
				} else {
					location.replace(url);
				}
				// #endif
               
			});
			
		},
		methods: {
			onGetMessage: function (data) {
				var val = data.detail.data[0];
				if (val && val.downloadbase64) {
					this.saveImageToPhotosAlbum(val.downloadbase64);
				} else if (val && val.daohang) {
					uni.openLocation({
						...JSON.parse(val.daohang)
					});
				} else if (val && val.listPageNeedUpdate) {
					global.listPageNeedReload = true;
				} else if (val && val.refreshUrl) {
					this.refreshUrl = val.refreshUrl;
				} else if (val && val.doQrScan) {
					global.scanItem = val.doQrScan;
					this.scanQrCode();
					uni.navigateTo({
						url: '/pages/openh5/index?title=' + (this.title || '') + '&url=' + encodeURIComponent(this.urlto)
					})
				}				
			},
			saveImageToPhotosAlbum(base64Str){
                var vm = this;
                let base64=base64Str.replace(/^data:image\/\w+;base64,/, "");//去掉data:image/png;base64,
                let filePath=wx.env.USER_DATA_PATH + '/' + vm.$Util.uuid() + '.png';
                uni.getFileSystemManager().writeFile({
                    filePath:filePath ,  //创建一个临时文件名
                    data: base64,    //写入的文本或二进制数据
                    encoding: 'base64',  //写入当前文件的字符编码
                    success: res => {
                        uni.saveImageToPhotosAlbum({
                            filePath: filePath,
                            success: function(res2) {
                                uni.showToast({
                                    title: '保存成功，请从相册选择再分享',
                                    icon:"none",
                                    duration:5000
                                })
								uni.navigateTo({
								    url: '/pages/openh5/index?title=' + vm.title + '&url=' + encodeURIComponent(vm.urlto)
								})
                            },
                            fail: function(err) {
                                // console.log(err.errMsg);
                            }
                        })
                    },
                    fail: err => {
                        //console.log(err)
                    }
                })
            }
        },
		
	}
</script>

<style lang="scss" scoped>
.viewImage {
    width: 750rpx;
}
</style>